<template>
  <div class="history">
    <van-cell class="controlTools">
      <span slot="title">历史记录</span>
      <div v-if="icon_text" class="controlItem">
        <span @click="deleteHistory">全部删除</span>
        <span @click="icon_text = false">完成</span>
      </div>
      <van-icon name="delete-o" v-else @click="icon_text = true" />
    </van-cell>
    <van-cell
      v-for="(item, index) in historyList"
      :key="index"
      :title="item"
      @click="toSearch(item)"
    >
      <van-icon name="close" v-if="icon_text" @click="removeHistroy(index)" />
    </van-cell>
  </div>
</template>

<script>
// 导入搜索历史api,删除历史
import { getSearchHistory, deleteHistory } from '@/assets/api/search.js'

export default {
  name: 'history',
  data() {
    return {
      // 搜索历史列表
      historyList: [],
      // toggle文字
      icon_text: false
    }
  },
  methods: {
    // 获取搜索历史
    async getHistory() {
      // 判断是否登入
      if (!this.$store.state.user) {
        return false
      }
      // 发起ajax请求拿到数据
      try {
        var { data: res } = await getSearchHistory()
      } catch {
        return this.$toast('获取历史数据失败，请稍后重试')
      }
      this.historyList = res.data.keywords
    },
    // 删除历史记录
    async deleteHistory() {
      if (!this.$store.state.user) {
        return false
      }

      // 发起ajax请求
      try {
        var { data: res } = await deleteHistory()
      } catch {
        return this.$toast('删除失败')
      }
      this.historyList = []
    },
    // 搜索结果
    toSearch(item) {
      if (this.icon_text) {
        return false
      }
      this.$emit('searchRult', item)
    },
    // 虚假的删除搜索历史,api文档没有相应的接口
    removeHistroy(index) {
      this.historyList.splice(index, 1)
    }
  },
  mounted() {
    this.getHistory()
  }
}
</script>

<style lang="less" scoped>
/deep/ .controlTools {
  .controlItem {
    span {
      margin-left: 15px;
    }
  }
}
</style>
